package com.cyj.comment.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.cyj.comment.entity.SeckillVoucher;
import com.cyj.comment.entity.VoucherOrder;
import com.cyj.comment.mapper.VoucherOrderMapper;
import com.cyj.comment.service.SeckillVoucherService;
import com.cyj.comment.service.VoucherOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cyj.comment.service.VoucherService;
import com.cyj.comment.utils.RedisIdWorker;
import com.cyj.comment.utils.Result;
import com.cyj.comment.utils.SimpleRedisLock;
import com.cyj.comment.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.connection.stream.*;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author chixiaowai
 * @since 2023-04-04
 */
@Slf4j
@Service
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements VoucherOrderService {
    @Autowired
    private SeckillVoucherService seckillVoucherService;
    @Autowired
    private RedisIdWorker redisIdWorker;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private RedissonClient redissonClient;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    private VoucherOrderService proxy;

    private static final DefaultRedisScript<Long> SECKILL_SCRIPT;

    static {
        SECKILL_SCRIPT = new DefaultRedisScript<>();
        SECKILL_SCRIPT.setLocation(new ClassPathResource("seckill.lua"));
        SECKILL_SCRIPT.setResultType(Long.class);
    }

    //阻塞队列
//    private BlockingQueue<VoucherOrder> orderTasks = new ArrayBlockingQueue<>(1024 * 1024);

    //线程池
    private static final ExecutorService SECKILL_ORDER_EXECUTOR = Executors.newSingleThreadExecutor();

    //在当前类初始化完毕后执行
//    @PostConstruct
//    private void init() {
//        SECKILL_ORDER_EXECUTOR.submit(new VoucherOrderHandler());
//    }

    //消息队列线程任务
//    private class VoucherOrderHandler implements Runnable {
//        String queueName = "stream.orders";
//        @Override
//        public void run() {
//            while (true) {
//                try {
//                    //获取消息队列中的订单信息 XREADGROUP GROUP g1 c1 COUNT 1 BLOCK 2000 STREAMS stream.orders >
//                    List<MapRecord<String, Object, Object>> msgList = stringRedisTemplate.opsForStream().read(
//                            Consumer.from("g1", "c1"),
//                            StreamReadOptions.empty().count(1).block(Duration.ofSeconds(2)),
//                            StreamOffset.create(queueName, ReadOffset.lastConsumed())
//                    );
//                    //判断消息是否获取成功
//                    if (msgList == null || msgList.isEmpty()) {
//                        //获取失败进行下一次循环
//                        continue;
//                    }
//                    //获取成功，解析消息
//                    MapRecord<String, Object, Object> record = msgList.get(0);
//                    Map<Object, Object> value = record.getValue();
//                    //转为voucherOrder对象
//                    VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(value, new VoucherOrder(), true);
//                    //创建订单
//                    handleVoucherOrder(voucherOrder);
//                    //确认消息
//                    stringRedisTemplate.opsForStream().acknowledge(queueName, "g1", record.getId());
//                } catch (Exception e) {
//                    log.error("处理订单异常", e);
//                    //从pendingList中读取消息
//                    handlePendingList();
//                }
//            }
//        }
//
//        /**
//         * 从pendingList中读取消息
//         */
//        private void handlePendingList() {
//            while (true) {
//                try {
//                    //获取消息队列中的订单信息  XREADGROUP GROUP g1 c1 COUNT 1 STREAMS stream.orders 0
//                    List<MapRecord<String, Object, Object>> msgList = stringRedisTemplate.opsForStream().read(
//                            Consumer.from("g1", "c1"),
//                            StreamReadOptions.empty().count(1),
//                            StreamOffset.create(queueName, ReadOffset.from("0"))
//                    );
//                    //判断消息是否获取成功
//                    if (msgList == null || msgList.isEmpty()) {
//                        //获取失败结束循环
//                        break;
//                    }
//                    //获取成功，解析消息
//                    MapRecord<String, Object, Object> record = msgList.get(0);
//                    Map<Object, Object> value = record.getValue();
//                    //转为voucherOrder对象
//                    VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(value, new VoucherOrder(), true);
//                    //创建订单
//                    handleVoucherOrder(voucherOrder);
//                    //确认消息
//                    stringRedisTemplate.opsForStream().acknowledge(queueName, "g1", record.getId());
//                } catch (Exception e) {
//                    log.error("处理订单异常", e);
//                    try {
//                        Thread.sleep(50);
//                    } catch (InterruptedException interruptedException) {
//                        interruptedException.printStackTrace();
//                    }
//                }
//            }
//        }
//
//    }


    //阻塞队列的线程任务
//    private class VoucherOrderHandler implements Runnable {
//
//        @Override
//        public void run() {
//            while (true) {
//                try {
//                    //获取阻塞队列中的订单信息
//                    VoucherOrder voucherOrder = orderTasks.take();
//                    //创建订单
//                    handleVoucherOrder(voucherOrder);
//                } catch (Exception e) {
//                    log.error("处理订单异常", e);
//                }
//            }
//        }
//    }

    public void handleVoucherOrder(VoucherOrder voucherOrder) {
        //获取用户
        Long userId = voucherOrder.getUserId();
        //创建锁对象
        RLock lock = redissonClient.getLock("lock:order:" + userId);
        boolean isLock = lock.tryLock();
        if (!isLock) {
            //获取锁失败
            log.error("不允许重复下单");
            return;
        }
        try {
            //拿到当前对象的代理对象
            proxy.createVoucherOrder(voucherOrder);
        } finally {
            lock.unlock();
        }
    }

    @Override
    public Result seckillVoucher(Long voucherId) {
        Long userId = UserHolder.getUser().getId();
        //订单id
        long orderId = redisIdWorker.nextID("order");
        //执行lua脚本，判断有没有购买资格
        Long result = stringRedisTemplate.execute(
                SECKILL_SCRIPT,
                Collections.emptyList(),
                voucherId.toString(), userId.toString(), String.valueOf(orderId)
        );
        int r = result.intValue();
        //判断结果是否为0，0为有资格，非0为没有资格
        if (r != 0) {
            //不为0，代表没有资格购买
            return Result.fail(r == 1 ? "库存不足" : "不能重复下单");
        }
        VoucherOrder voucherOrder = new VoucherOrder();
        voucherOrder.setId(orderId);
        voucherOrder.setUserId(userId);
        voucherOrder.setVoucherId(voucherId);
        //存入消息队列
        rabbitTemplate.convertAndSend("seckill_exchange", "order.voucher", voucherOrder);

        //获取代理对象
        proxy = (VoucherOrderService) AopContext.currentProxy();
        //返回订单id
        return Result.ok(orderId);
    }

    /*@Override
    public Result seckillVoucher(Long voucherId) {
        Long userId = UserHolder.getUser().getId();
        //执行lua脚本，判断有没有购买资格
        Long result = stringRedisTemplate.execute(
                SECKILL_SCRIPT,
                Collections.emptyList(),
                voucherId.toString(), userId.toString()
        );
        int r = result.intValue();
        //判断结果是否为0，0为有资格，非0为没有资格
        if (r != 0) {
            //不为0，代表没有资格购买
            return Result.fail(r == 1 ? "库存不足" : "不能重复下单");
        }
        //为0，有资格购买，将订单信息保存到阻塞队列中
        //创建订单
        long orderId = redisIdWorker.nextID("order");
        VoucherOrder voucherOrder = new VoucherOrder();
        voucherOrder.setId(orderId);
        voucherOrder.setVoucherId(voucherId);
        voucherOrder.setUserId(userId);
        //添加到阻塞队列
        orderTasks.add(voucherOrder);
        //获取代理对象
        proxy = (VoucherOrderService) AopContext.currentProxy();
        //返回订单id
        return Result.ok(orderId);
    }*/

 /*   @Override
    public Result seckillVoucher(Long voucherId) {
        //1、查询优惠券
        SeckillVoucher voucher = seckillVoucherService.getById(voucherId);
        //2、判断秒杀是否开始
        if (voucher.getBeginTime().isAfter(LocalDateTime.now())) {
            //未开始
            return Result.fail("秒杀尚未开始");
        }
        //3、判断秒杀是否结束
        if (voucher.getEndTime().isBefore(LocalDateTime.now())) {
            //已结束
            return Result.fail("秒杀已经结束");
        }
        //4、判断库存是否充足
        if (voucher.getStock() < 1) {
            return Result.fail("已经被抢光了");
        }
//        Long userId = UserHolder.getUser().getId();
        //创建锁对象
//        SimpleRedisLock lock = new SimpleRedisLock("order:" + userId, stringRedisTemplate);
//        boolean isLock = lock.tryLock(1200);
//        RLock lock = redissonClient.getLock("lock:order:" + userId);
//        boolean isLock = lock.tryLock();
//        if (!isLock) {
//            //获取锁失败
//            return Result.fail("已经购买过了");
//        }
//        try {
//            //拿到当前对象的代理对象
//            VoucherOrderService proxy = (VoucherOrderService) AopContext.currentProxy();
//            return proxy.createVoucherOrder(voucherId);
//        } finally {
//            lock.unlock();
//        }
        return createVoucherOrder(voucherId);
    }*/

    @Transactional
    public void createVoucherOrder(VoucherOrder voucherOrder) {
        //5、一人一单
        Long userId = voucherOrder.getUserId();
        //创建锁对象
        RLock lock = redissonClient.getLock("lock:order:" + userId);
        boolean isLock = lock.tryLock();
        if (!isLock) {
            //获取锁失败
            log.error("已经购买过了");
            return;
        }
        //5.1、查询该用户的订单
        Long voucherId = voucherOrder.getVoucherId();
        int count = query().eq("user_id", userId).eq("voucher_id", voucherId).count();
        //5.2、判断订单是否存在
        if (count > 0) {
            //订单已经存在返回提示信息
            log.error("已经购买过了");
            return;
        }
        //6、扣减库存
        boolean success = seckillVoucherService.
                update().setSql("stock = stock - 1")
                .eq("voucher_id", voucherId)
                //乐观锁
                .gt("stock", 0)
                .update();
        //扣减失败，一般也是因为库存不足导致的
        if (!success) {
            log.error("已经被抢光了");
            return;
        }
        //8、返回订单id
        save(voucherOrder);
        lock.unlock();
    }

//    @Transactional
//    public Result createVoucherOrder(Long voucherId) {
//        //5、一人一单
//        Long userId = UserHolder.getUser().getId();
//        //创建锁对象
//        RLock lock = redissonClient.getLock("lock:order:" + userId);
//        boolean isLock = lock.tryLock();
//        if (!isLock) {
//            //获取锁失败
//            return Result.fail("已经购买过了");
//        }
//        try {
//            //5.1、查询该用户的订单
//            int count = query().eq("user_id", userId).eq("voucher_id", voucherId).count();
//            //5.2、判断订单是否存在
//            if (count > 0) {
//                //订单已经存在返回提示信息
//                return Result.fail("已经购买过了");
//            }
//            //6、扣减库存
//            boolean success = seckillVoucherService.
//                    update().setSql("stock = stock - 1")
//                    .eq("voucher_id", voucherId)
//                    //乐观锁
//                    .gt("stock", 0)
//                    .update();
//            //扣减失败，一般也是因为库存不足导致的
//            if (!success) {
//                return Result.fail("已经被抢光了");
//            }
//            //7、创建订单
//            VoucherOrder voucherOrder = new VoucherOrder();
//            //7.1、订单id
//            long orderId = redisIdWorker.nextID("order");
//            voucherOrder.setId(orderId);
//            //7.2、用户id
//            voucherOrder.setUserId(userId);
//            //7，3、代金券id
//            voucherOrder.setVoucherId(voucherId);
//            //8、返回订单id
//            save(voucherOrder);
//            return Result.ok(orderId);
//        } finally {
//            lock.unlock();
//        }
//    }
}
